package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Override
    public Cart add(Cart cartParam) {
        //先判断购物车中是否有数据
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        //获取用户id
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        // 菜品id 动态sql
        qw.eq(cartParam.getDishId() != null, Cart::getDishId, cartParam.getDishId());
        // 套餐id 动态sql
        qw.eq(cartParam.getSetmealId() != null, Cart::getSetmealId, cartParam.getSetmealId());
        Cart cart = cartMapper.selectOne(qw);
        // 2.判断,如果为空，新增一条记录
        if (cart == null) {
            cartParam.setNumber(1);
            cartParam.setCreateTime(new Date());
            cartParam.setUserId(UserHolder.get().getId());
            cartMapper.insert(cartParam);
            cart = cartParam;
        }else {
            cart.setNumber(cartParam.getNumber() + 1);
            cartMapper.updateById(cart);
        }
        return cart;
    }

    @Override
    public List<Cart> findList() {
        //查询
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        return cartMapper.selectList(qw);
    }

    @Override
    public Cart update(Cart cart) {
        //判断购物车是否有数据
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        // 套餐id 动态sql
        qw.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        // 菜品id 动态sql
        qw.eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId());
        Cart cart1 = cartMapper.selectOne(qw);
        //判断
        if (cart1.getNumber() <= 1 ) {
            cartMapper.deleteById(cart1.getId());
        }else {
            cart1.setNumber(cart1.getNumber() - 1);
            cartMapper.updateById(cart1);
        }
        return cart;
    }

    @Override
    public void clean() {
        //构造条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(qw);
    }
}
